package com.nsy.shortlink.project.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.nsy.shortlink.project.common.convention.result.Result;
import com.nsy.shortlink.project.common.convention.result.Results;
import com.nsy.shortlink.project.dto.req.ShortLinkCreateReqDTO;
import com.nsy.shortlink.project.dto.req.ShortLinkPageReqDTO;
import com.nsy.shortlink.project.dto.req.ShortLinkUpdateReqDTO;
import com.nsy.shortlink.project.dto.resp.ShortLinkCreateRespDTO;
import com.nsy.shortlink.project.dto.resp.ShortLinkGroupCountQueryRespDTO;
import com.nsy.shortlink.project.dto.resp.ShortLinkPageRespDTO;
import com.nsy.shortlink.project.handler.CustomBlockHandler;
import com.nsy.shortlink.project.service.ShortLinkService;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.List;

/**
 * @className: ShortLinkController
 * @author: 宁舒意
 * @description: TODO
 * @date: 2024/10/5 11:02
 */
@RestController
@RequiredArgsConstructor
public class ShortLinkController {
    private final ShortLinkService shortLinkService;

    /**
     * 创建短链接
    **/
    @PostMapping("/api/short-link/v1/create")
//    @SentinelResource(
//            value = "create_short-link",
//            blockHandler = "createShortLinkBlockHandlerMethod",
////            如果限流了就执行CustomBlockHandler中的createShortLinkBlockHandlerMethod方法
//            blockHandlerClass = CustomBlockHandler.class
//    )
    public Result<ShortLinkCreateRespDTO> createShortLink(@RequestBody ShortLinkCreateReqDTO requestParam){
        return Results.success(  shortLinkService.createShortLink(requestParam));
    }


    @GetMapping("/api/short-link/admin/v1/page")
    public Result<IPage<ShortLinkPageRespDTO>> pageShortLink(ShortLinkPageReqDTO requestParam){
        return Results.success(shortLinkService.pageShortLink(requestParam));
    }

    /**
     * 这里传数组记得加@RequestParam注解
    **/
    @GetMapping("/api/short-link/v1/count")
    public Result<List<ShortLinkGroupCountQueryRespDTO>> listShortLinkGroup(@RequestParam List<String> requestParam){
        return Results.success(shortLinkService.listShortLinkGroup(requestParam));
    }

    @PostMapping("/api/short-link/admin/v1/update")
    public  Result<Void> updateShortLink(@RequestBody ShortLinkUpdateReqDTO requestParam){
        shortLinkService.updateShortLink(requestParam);
        return Results.success();

    }


    /**
     * 短链接跳转
    **/
    @GetMapping("/{short-uri}")
    public void restoreUrl(@PathVariable("short-uri") String shortUri, HttpServletRequest request, HttpServletResponse response) throws IOException {
        shortLinkService.restoreUri(shortUri,request,response);


    }
}

